//
//  ChatItemUserPictureView.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/5/2.
//

import SwiftUI
import Kingfisher

//用户聊天图片
struct ChatItemUserPictureView: View {
    @ObservedObject var viewModel : ChatViewModel
    @State var item: ChatBean
    @State private var showDel = false //删除
    @State private var showFullScreen = false //预览图片
    @State private var selectedIndex = 0
    @State private var hignBg = false //高亮背景
    @State private var select = false //选中

    var body: some View {
        HStack(alignment:.top, spacing: 10) {
            if viewModel.choose {
                chooseView
                Spacer()
            }
            contentView
            ChatAvatarVeiw(item: item)
        }.frame(maxWidth: .infinity,alignment: .topTrailing)
            .padding(EdgeInsets(top: 10, leading: 15, bottom: 20, trailing: 15))
            .background {
                if hignBg {
                    themeManager.themeColor.opacity(0.2)
                }
            }
            .contextMenu{
                if !viewModel.choose {
                    Button("删除") {
                        hideKeyboard()
                        showDel = true
                    }
                    Button("复制") {
                        showToast("复制成功")
                        copyClipboard(item.content)
                    }
                    Button("引用") {
                        hideKeyboard()
                        if !AppStorageManager.shared.checkChatFuncToggle() {
                            return
                        }
                        viewModel.targetChatBean = item
                    }
                    Button("多选") {
                        viewModel.setChooseMode()
                    }
                }
            }
            .alert("温馨提示",isPresented:$showDel) {
                Button("取消",role: .cancel){}
                Button("确定",role: .destructive) {
                    viewModel.delChat(bean: item)
                }
            } message: {
                Text("是否确定要删除")
            }.onReceive(viewModel.$scrollChat.dropFirst()) { value in
                if value == item.objectId {
                    //搜索id一致，则高亮
                    withAnimation {
                        hignBg = true
                    }
                    DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
                        withAnimation {
                            hignBg = false
                        }
                    }
                }
            }
            .onChange(of: select) { newValue in
                item.select = newValue
            }
            .overlay {
                if viewModel.choose {
                    Color.clear
                        .contentShape(Rectangle())
                        .onTapGesture {
                            select = !select
                        }
                }
            }
    }
}

extension ChatItemUserPictureView {
    var contentView : some View {
        VStack {
            let picture = parsePicture()
            let calculateSize = calculateSize(picture: picture)
            let itemWidth = calculateSize.width
            let itemHeight = calculateSize.height
            if let mediaItem = EmojiPictureUtils.shared.getMediaItem(picture) {
                PictureItemView(item: mediaItem, itemWidth: itemWidth, itemHeight: itemHeight, cornerRadius: 0)
                    .contentShape(Rectangle())
                    .onTapGesture {
                        showFullScreen = true
                    }
                    .fullScreenCover(isPresented: $showFullScreen) {
                        FullScreenMediaView(mediaItems: [mediaItem], currentIndex: $selectedIndex)
                    }
            } else {
                Image(.appDefaultLogo)
                    .resizable()
                    .scaledToFill()
                    .frame(width: 100,height: 100)
                    .padding(.horizontal, itemWidth / 4)
                    .padding(.vertical, itemWidth / 4)
            }
        }
        .clipShape(RoundedRectangle(cornerRadius: 5))
        .overlay(
            ZStack{
                //圆角边框，比border效果好
                RoundedRectangle(cornerRadius: 5)
                    .stroke(Color.disabled, lineWidth: 1)
                
            }
        )
    }
    
    private func parsePicture() -> EmojiPictureBean? {
        do {
            return try fromJson(item.extra ?? "", EmojiPictureBean.self)
        } catch {
            showLog("解析错误: \(error)")
            return nil
        }
    }
    
    func calculateSize(picture: EmojiPictureBean?) -> (width: CGFloat, height: CGFloat) {
        let maxDimension: CGFloat = 200
        let minDimension: CGFloat = 60
        guard let picture = picture else {
            return (width: maxDimension, height: minDimension)
        }
        
        let originalWidth = CGFloat(picture.width ?? 0)
        let originalHeight = CGFloat(picture.height ?? 0)
        let aspectRatio = originalWidth / originalHeight
        
        if originalWidth > originalHeight {
            // 横图：以宽为基准缩放
            let width = min(originalWidth, maxDimension)
            var height = width / aspectRatio
            if height < minDimension {
                height = minDimension
            }
            return (width: width, height: height)
        } else {
            // 竖图或正方形：以高为基准缩放
            let height = min(originalHeight, maxDimension)
            var width = height * aspectRatio
            if width < minDimension {
                width = minDimension
            }
            return (width: width, height: height)
        }
    }
}

extension ChatItemUserPictureView {
    //多选试图
    private var chooseView: some View {
        Group {
            if select == true {
                Image(.appIcCheckboxSelect)
                    .resizable()
                    .renderingMode(.template)
                    .foregroundColor(themeManager.themeColor)
                    .frame(width: 20,height: 20)
                    .padding(.top, 10)
            } else {
                Image(.appIcCheckbox)
                    .resizable()
                    .frame(width: 20,height: 20)
                    .padding(.top, 10)
            }
        }.onAppear{
            select = item.select ?? false
        }
    }
}

#Preview {
    ChatItemUserPictureView(viewModel: ChatViewModel(),item: ChatBean()).background(.bg)
}
